package com.jtbd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jtbd.config.CustomAuthentication;
import com.jtbd.constants.ResponseCodeEnum;
import com.jtbd.domain.UserInfo;
import com.jtbd.exceptions.SystemException;
import com.jtbd.mapper.UserInfoMapper;
import com.jtbd.service.UserInfoService;
import com.jtbd.dto.UserAuthDetailsEntity;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

/**
 * 用户信息服务实现类
 */
@Service
@Slf4j
public class UserInfoServiceImpl implements UserInfoService {
    @Resource
    private UserInfoMapper userInfoMapper;
    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public Long userLogin(HttpServletResponse response, String phone, Integer userType, String password) {
        log.error("用户登录：phone={} usertype={}", phone, userType);
        if (ObjectUtils.isEmpty(phone)) {
            throw new SystemException(ResponseCodeEnum.ERROR.getCode(), "手机号不能为空！");
        }
        if (ObjectUtils.isEmpty(password)) {
            throw new SystemException(ResponseCodeEnum.ERROR.getCode(), "密码不能为空！");
        }
        //封装认证信息 并进行用户登录及认证
        UserAuthDetailsEntity userAuthDetails1 = new UserAuthDetailsEntity();
        userAuthDetails1.setPhone(phone);
        userAuthDetails1.setPassword(password);
        userAuthDetails1.setUserType(userType);
        Authentication authenticate = authenticationManager.authenticate(new CustomAuthentication(userAuthDetails1));
        //检测认证结果是否成功
        if (!ObjectUtils.isEmpty(authenticate) && authenticate.isAuthenticated()) {
            log.error("用户登录成功：{}", authenticate);
            //从认证结果中获取用户身份
            Object principal = authenticate.getPrincipal();
            //判断用户身份是否为UserAuthDetailsEntity类型的数据
            if (principal instanceof UserAuthDetailsEntity userAuthDetails) {
                // 获取uid 用户获取完整的用户信息
                return userAuthDetails.getUid();
            }
        }
        throw new SystemException(ResponseCodeEnum.ERROR_LOGIN.getCode(), ResponseCodeEnum.ERROR_LOGIN.getMsg());
    }

    @Override
    public UserInfo getUserIdByPhoneAndType(String phone, Integer userType) {
        // 根据手机号查询用户信息
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getPhone, phone);
        queryWrapper.eq(UserInfo::getUserType, userType);
        return userInfoMapper.selectOne(queryWrapper);
    }

    @Override
    public UserInfo getUserInfo(Long uid) {
        return userInfoMapper.selectById(uid);
    }

    @Override
    public Long addUserInfo(UserInfo userInfo) {
        log.error("添加用户：{}", userInfo);
        if (ObjectUtils.isEmpty(userInfo)) {
            throw new SystemException(ResponseCodeEnum.ERROR.getCode(), "用户信息不能为空！");
        }
        if (ObjectUtils.isEmpty(userInfo.getPhone())) {
            throw new SystemException(ResponseCodeEnum.ERROR.getCode(), "手机号不能为空！");
        }
        if (ObjectUtils.isEmpty(userInfo.getPassword())) {
            throw new SystemException(ResponseCodeEnum.ERROR.getCode(), "密码不能为空！");
        }
        if (ObjectUtils.isEmpty(userInfo.getUserType())) {
            throw new SystemException(ResponseCodeEnum.ERROR.getCode(), "用户类型不能为空！");
        }
        userInfo.setPassword(BCrypt.hashpw(userInfo.getPassword(), BCrypt.gensalt()));
        int insertResult = userInfoMapper.insert(userInfo);
        if (insertResult > 0) return userInfo.getId();
        return null;
    }
}
